import React, { useState, useEffect } from 'react'
import { Card, Button, Table, Modal, Form, Input, Select, message } from 'antd'
import { PlusCircleOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import ajax from '../../service/ajax'

const { Item } = Form
const { Option } = Select

export default function User() {
  const [userList, setUserList] = useState([])
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [roleOption, setRoleOption] = useState()
  const [form] = Form.useForm()
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '注册时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (create_time) => dayjs(create_time).format('YYYY年 MM月DD日 HH:mm:ss')
    },
    {
      title: '所属角色',
      // dataIndex: 'role_id',
      key: 'role_id',
      render: (item) => {
        if (roleOption) {
          let { name } = roleOption.find((role) => {
            return role._id === item.role_id
          })
          return name
        }
      }
    },
    {
      title: '操作',
      // dataIndex: 'operation',
      key: 'operation',
      align: 'center',
      render: () => (
        <div>
          <Button type='link'>修改</Button>
          <Button type='link'>删除</Button>
        </div>
      )
    }
  ];

  const showModal = () => {
    setIsModalVisible(true);
  };

  // 点击确认按钮实现添加用户
  const handleOk = async () => {
    let formValues = form.getFieldsValue()
    let { status, data, msg } = await ajax.post('/manage/user/add', formValues)
    if (status === 0) {
      message.success('添加用户成功')
      getUserList()
    } else {
      message.error(msg)
    }
    setIsModalVisible(false);
    form.resetFields()
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields()
  };


  useEffect(() => {
    getUserList()
  }, [])

  // 请求所有的角色列表
  useEffect(() => {
    getRoleList()
  }, [])

  const getRoleList = async () => {
    let { status, data, msg } = await ajax('/manage/role/list')
    // console.log(data)
    setRoleOption(data)
  }

  const getUserList = async () => {
    let { status, data, msg } = await ajax('/manage/user/list')
    setUserList(data.users.reverse())
    // console.log(data)
  }

  return (
    <Card
      title={
        <div>
          <Button
            type="primary"
            onClick={() => { showModal() }}
          >
            <PlusCircleOutlined />创建用户
          </Button>
        </div>
      }
    >
      <Table
        dataSource={userList}
        columns={columns}
        rowKey="_id"
        bordered
      />
      <Modal
        title="添加用户"
        cancelText="取消"
        okText="确认"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          initialValues={{ role_id: '' }}
        >
          <Item
            label="用户名"
            name="username"
            labelCol={{ span: 5 }}
            labelAlign="right"
            wrapperCol={{ span: 16 }}
            rules={[
              { required: true, message: '用户名不能为空' }
            ]}
          >
            <Input placeholder="请输入用户名" />
          </Item>
          <Item
            label="密码"
            name="password"
            labelCol={{ span: 5 }}
            labelAlign="right"
            wrapperCol={{ span: 16 }}
            rules={[
              { required: true, message: '密码不能为空' }
            ]}
          >
            <Input placeholder="请输入密码" />
          </Item>
          <Item
            label="手机号"
            name="phone"
            labelCol={{ span: 5 }}
            labelAlign="right"
            wrapperCol={{ span: 16 }}
            rules={[
              { required: true, message: '手机号不能为空' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Item>
          <Item
            label="邮箱"
            name="email"
            labelCol={{ span: 5 }}
            labelAlign="right"
            wrapperCol={{ span: 16 }}
            rules={[
              { required: true, message: '邮箱不能为空' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Item>
          <Item
            label="角色"
            name="role_id"
            labelCol={{ span: 5 }}
            labelAlign="right"
            wrapperCol={{ span: 16 }}
            rules={[
              { required: true, message: '角色不能为空' }
            ]}
          >
            <Select>
              <Option value="">请选择一个角色</Option>
              {
                roleOption && roleOption.map((role) => {
                  return <Option value={role._id} key={role._id}>{role.name}</Option>
                })
              }
            </Select>
          </Item>
        </Form>
      </Modal>
    </Card>
  )
}